<script setup lang="ts">
// import Personage from './components/Personage.vue'
import OrderModule from './components/OrderModule.vue'
import OrderStatus from './components/OrderStatus.vue'
import { ref, watch, inject, nextTick } from 'vue'
import { onHide, onLoad, onShow } from '@dcloudio/uni-app'
import { getBannerListApi, getMachineDataApi } from '@/services/home'
import {
  useDeviceStore,
  useLocationStore,
  useMemberStore,
  usePhoneStore,
  usePagesMachineIdStore,
} from '@/stores'
import unfinishedPopup from './components/unfinishedPopup.vue'
import { postActivityDegreeApi } from '@/services/component'

const locationStore = useLocationStore()
const memberStore = useMemberStore() // 本地有缓存的 token 不调用临时 token
const phoneStore = usePhoneStore()
const deviceStore = useDeviceStore()
const pagesMachineId = usePagesMachineIdStore()
const { deviceId } = uni.getSystemInfoSync() // 获取登录设备信息
const { loginPromise } = <{ loginPromise: Promise<unknown> }>inject('globalData')

const clientRect = ref({})
onLoad((ev) => {
  console.log('onLoad', ev)
  ev?.machineId ? pagesMachineId.setPagesMachineId(ev.machineId) : null
  loginPromise.then(() => {
    getMachineList()
  })
  clientRect.value = uni.getMenuButtonBoundingClientRect()
})

/**
 * * 获取当前地点最近的设备并且赋值
 * @param machineName 设备名称
 */
const getMachineList = async () => {
  let itemDevice
  try {
    const res = await getMachineDataApi({
      machineId: pagesMachineId.pagesMachineId || null,
      clientId: memberStore.userInfo?.id || '',
      longitude: locationStore.location!.longitude,
      latitude: locationStore.location!.latitude,
      pageNum: 1,
      pageSize: 50,
    })

    itemDevice = res.data?.find((item: any) => {
      if (item.machineId === pagesMachineId.pagesMachineId) return item
    })
    console.log('itemDevice', itemDevice)
    if (!itemDevice || Object.keys(itemDevice).length === 0) {
      itemDevice = res.data?.find((item: any) => {
        if (item.businessStatus === '运营中') return item
      })
    }
    deviceStore.setDeviceInfo(itemDevice)
  } catch (error) {
    console.log(error)
  }
  postActivityDegreeApi({
    machineId: itemDevice?.machineId,
    temporarySign: memberStore.token ? null : deviceId,
  })
}

/**
 *  imageList 轮播图数据
 */
const imageList = ref([
  {
    resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/home_up.png',
  },
  {
    resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/home_up.png',
  },
  {
    resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/home_up.png',
  },
])
/** 下面广告轮播 */
const BannerList = ref([
  { resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/home_bot.png' },
])
const popupRef = ref()
const unfinishedPopupRef = ref()
const OrderModuleRef = ref()
const PersonageRef = ref()
// 公共弹出框
import usePopup from '@/hooks/usePopup'
const { SkipPopupRef, receive, skipPopupData, handleClose } = usePopup()

onShow(() => {
  if (memberStore.token) {
    getOrderStatusTips()
    openSetInterval()
  }
  // console.log('====================-===onShow', skipPopupData)
  console.log(loginPromise)
  loginPromise
    .then(() => {
      // console.log('loginPromise==========================')
      getBannerList()
    })
    .catch(() => {
      // console.log('loginPromise==========================catch')
      getBannerList()
    })
})

// 调用小程序的分享，以及监听小程序分享
import useMiniShare from '@/hooks/useMiniShare'
import { getOrderStatusTipsApi } from '@/services/goods'
const { isShareFriends, onShareTimeline, onShareAppMessage, setupOnShareAppMessage } =
  useMiniShare()

isShareFriends(true)
onShareAppMessage
onShareTimeline // 监听朋友圈分享

// 监听本地缓存的设备信息是否变化，改变分享链接的设备id
watch(
  () => deviceStore.deviceInfo,
  (newVal, oidVal) => {
    if (newVal !== oidVal && newVal !== undefined) {
      const shareParams = {
        path: `/pages/index/index?machineId=${deviceStore.deviceInfo?.machineId}&machineName=${deviceStore.deviceInfo?.machineName}&positionAddr=${deviceStore.deviceInfo?.positionAddr}&businessStatus=${deviceStore.deviceInfo?.businessStatus}&saleBeginTime=${deviceStore.deviceInfo?.saleBeginTime}&saleEndTime=${deviceStore.deviceInfo?.saleEndTime}`,
        title: newVal.machineName,
      }
      setupOnShareAppMessage(shareParams)
    }
  },
  {
    deep: true,
    immediate: true,
  },
)

/**获取 banner 列表 */
const getBannerList = async () => {
  try {
    const res = await getBannerListApi(locationStore.location?.cityName)
    console.log(res)
    if (res.data.hostBanners) {
      imageList.value = res.data.hostBanners.map((item: any) => {
        return {
          ...item,
          resourceUrl: item.img,
        }
      })
    }
    if (res.data.hostBottomBanners) {
      BannerList.value = res.data.hostBottomBanners.map((item: any) => {
        return {
          ...item,
          resourceUrl: item.img,
        }
      })
    }
  } catch (error) { }
}
const orderInfo = ref<any>()
/** 获取订单状态提示 */
const getOrderStatusTips = async () => {
  const res = await getOrderStatusTipsApi()
  console.log('获取订单状态提示', res)
  orderInfo.value = res.data
}
let polling = ref()
/**开启轮询 */
const openSetInterval = () => {
  polling.value = setInterval(() => {
    getOrderStatusTips()
  }, 5000)
}
onHide(() => {
  clearInterval(polling.value)
  OrderStatusRef.value.tipsShow = false
})
const OrderStatusRef = ref()

const getCity = () => {
  return JSON.parse(uni.getStorageSync('location'))?.location?.cityName || '杭州市'
}
</script>

<template>
  <view @tap="OrderStatusRef.tipsShow = false">
    <view class="headNavigationBar" :style="{ paddingTop: Number(phoneStore.phoneInfo!.top) + 2 + 'px' }">
      <view class="location_button">{{ deviceStore.deviceInfo?.machineName || getCity() }}</view>
    </view>
    <!-- 背景图 -->
    <view class="bgcImage" :style="{ marginTop: Number(clientRect?.top + clientRect?.height) + 6 + 'px' }">
      <BjsSwiper @goToLogin="popupRef?.open" :list="imageList" :flag="false" />
    </view>
    <view class="index">
      <!-- @unfinishedOpen="unfinishedPopupRef!.unfinishedOpen()" 开启点击提示（未开发弹窗） -->

      <!-- <Personage @open="popupRef!.open()" ref="PersonageRef" class="Personage" /> -->
      <!-- 有订单的时候展示组件 -->
      <OrderStatus v-if="orderInfo" :orderInfo="orderInfo" ref="OrderStatusRef" :orderId="'123'" />

      <OrderModule ref="OrderModuleRef" @open="popupRef!.open()" />
      <view class="Banner">
        <!-- <image :src="BannerList[0].resourceUrl" mode="scaleToFill" /> -->
        <BjsSwiper @goToLogin="popupRef?.open" :list="BannerList" :flag="false" />
      </view>
    </view>
  </view>
  <!-- 公共弹窗 -->
  <BjsPopup ref="popupRef" />
  <unfinishedPopup ref="unfinishedPopupRef" />
  <BjsSkipPopup :img="skipPopupData.img" ref="SkipPopupRef" @receive="receive" @changeVal="PersonageRef.getMyCoupons()"
    @close="handleClose" />
  <!--  @getMyCoupons="OrderModuleRef?.getMyCoupons" -->
</template>

<style lang="scss" scoped>
page {
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  min-height: 50%;
}

.headNavigationBar {
  position: absolute;
  top: 0;
  display: flex;
  justify-content: space-between;
  width: 100%;
  z-index: 9;

  .location_button {
    margin-left: 30rpx;
    padding: 0 28rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    border-radius: 68rpx;
    background-color: #fff2d3;
    color: #000;
    font-size: 24rpx;
    opacity: 0.9;
  }

  .iconfont {
    width: 56rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    font-size: 32rpx;
    color: $uni-color-motif;
    border-radius: 50%;
    background: #eff8f1;
  }
}

.index {
  padding: 0 24rpx;
  margin-top: -40rpx;
  position: relative;

  .Personage {
    z-index: 99;
  }

  .Banner {
    margin: 30rpx 0 24rpx;
    width: 702rpx;
    height: 182rpx;

    & image {
      border-radius: 16rpx;
    }
  }
}

.PopupRef {
  padding-bottom: 20px;
  background-color: #fff;
  box-sizing: content-box;
}

// 背景图
.bgcImage {
  height: 400rpx;
}
</style>
